package com.wly.jdbc;

import com.wly.domain.Student;
import com.wly.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wly
 * @Create 2023-04-30 10:57
 * @Description:使用JDBCUtils工具类
 */
public class JDBCDemo5 {
    public List<Student> findAll() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Student> students = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from student";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            Student student = null;
            students = new ArrayList<Student>();
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                String sex = rs.getString("sex");
                String address = rs.getString("address");
                //创建student对象，并赋值
                student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                student.setSex(sex);
                student.setAddress(address);
                students.add(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.close(rs, stmt, conn);
        }
        return students;
    }

    public static void main(String[] args) {
        JDBCDemo5 jdbcDemo5 = new JDBCDemo5();
        List<Student> list = jdbcDemo5.findAll();
        System.out.println(list);
    }
}
